package com.newgoldcurrency.activities.register;

import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.newgoldcurrency.R;
import com.newgoldcurrency.databinding.ActivityRegisterBinding;
import com.newgoldcurrency.utils.Tools;
import com.newgoldcurrency.utils.network.Network;
import com.newgoldcurrency.view.LoadingDialog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class RegisterActivity extends AppCompatActivity {
    private final List<Call> calls=new ArrayList<>();
    private ActivityRegisterBinding binding;
    private LoadingDialog loading_dialog;
    private ActivityResultLauncher<Intent> launcher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         binding = ActivityRegisterBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setResult(1);
        loading_dialog=new LoadingDialog(this);
        binding.registerNext.setOnClickListener(v ->{
            if (checkDoubleClick()) {
                if (loading_dialog != null && !loading_dialog.isShowing()) {
                    loading_dialog.show();
                    String country = binding.registerSpinner.getSelectedItem().toString();
                    if (country.equals("select")){
                        Tools.toast(getString(R.string.please_select_country));
                        binding.registerSpinner.startAnimation(AnimationUtils.loadAnimation(this, R.anim.shake_button));
                        loading_dialog.dismiss();
                        return;
                    }
                    String email=binding.registerEmail.getText().toString();
                    if (!Tools.isEmail(email)){
                        Tools.toast(getString(R.string.email_format_err));
                        loading_dialog.dismiss();
                        return;
                    }
                    if (!binding.registerCheck.isChecked()){
                        binding.registerCheck.startAnimation(AnimationUtils.loadAnimation(this, R.anim.shake_button));
                        Tools.toast(getString(R.string.check_text));
                        loading_dialog.dismiss();
                        return;
                    }
                    if (email.equals("")){
                        Tools.toast(getString(R.string.please_input_email));
                        loading_dialog.dismiss();
                    }else{
                        HashMap<String, String> map=new HashMap<>();
                        map.put("mail",binding.registerEmail.getText().toString());
                        Network.post(map, "user/verifyMailRegistered", call -> {
                            call.enqueue(new Callback() {
                                @Override
                                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                    runOnUiThread(() -> {
                                        e.printStackTrace();
                                        loading_dialog.dismiss();
                                    });
                                }
                                @Override
                                public void onResponse(@NonNull Call call, @NonNull Response response) {
                                    runOnUiThread(() -> {
                                        loading_dialog.dismiss();
                                        try {
                                            String str= Objects.requireNonNull(response.body()).string();
                                            if (Tools.isJson(str)){
                                                JsonObject jo = JsonParser.parseString(str).getAsJsonObject();
                                                if (jo.get("message").getAsString().equals("That email address is taken. Try another")){
                                                    launcher.launch(new Intent(RegisterActivity.this,RegisterMailOccupiedActivity.class));
                                                }else{
                                                    launcher.launch(new Intent(RegisterActivity.this,RegisterPasswordActivity.class).putExtra("country",country).putExtra("email",email));
                                                }
                                            }
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    });
                                }
                            });
                            calls.add(call);
                        });
                    }
                }
            }
        });
        binding.registerClose.setOnClickListener(v -> finish());
        String str="[\"select\",\"Afghanistan\",\"Albania\",\"Algeria\",\"American Samoa\",\"Andorra\",\"Angola\",\"Anguilla\",\"Antarctica\",\"Argentina\",\"Armenia\",\"Aruba\",\"Ascension\",\"Australia\",\"Austria\",\"Azerbaijan\",\"Bahamas\",\"Bahrain\",\"Bangladesh\",\"Barbados\",\"Belarus\",\"Belgium\",\"Belize\",\"Benin\",\"Bermuda\",\"Bhutan\",\"Bolivia\",\"Bosnia and herzegovina\",\"Botswana\",\"Bouvet island\",\"Brazil\",\"Britain\",\"Brunei\",\"Bulgaria\",\"Burkina Faso\",\"Burma\",\"Burundi\",\"Cameroon\",\"Canada\",\"Cape Verde\",\"Chad\",\"Chile\",\"China\",\"Christmas Island\",\"Columbia\",\"Comoros\",\"Congo\",\"Costa Rica\",\"Cote d'Ivoire\",\"Croatia\",\"Cuba\",\"Cyprus\",\"Czech Republic\",\"Denmark\",\"Djibouti\",\"Dominica\",\"East Timor\",\"Ecuador\",\"Egypt\",\"Eritrea\",\"Estonia\",\"Ethiopia\",\"Faroe Islands\",\"Fiji\",\"Finland\",\"France\",\"French guiana\",\"French polynesia\",\"Gabon\",\"Gambia\",\"Garner\",\"Georgia\",\"Germany\",\"Ghana\",\"Gibraltar\",\"Greece\",\"Greenland\",\"Grenada\",\"Guadeloupe\",\"Guam\",\"Guatemala\",\"Guernsey\",\"Guinea\",\"Guinea Bissau\",\"Guyana\",\"Haiti\",\"Hird and the Macdonald islands\",\"Holland\",\"Honduras\",\"HongKong\",\"Hungary\",\"Iceland\",\"India\",\"Indonesia\",\"Iran\",\"Iraq\",\"Ireland\",\"Israel\",\"Italy\",\"J Val Ba and Martin\",\"Jamaica\",\"Japan\",\"Jersey\",\"Jordan\",\"Kampuchea\",\"Kazakhstan\",\"Kenya\",\"Kiribati\",\"Korea\",\"Kuwait\",\"Kyrgyzstan\",\"Laos\",\"Latvia\",\"Lebanon\",\"Lesotho\",\"Liberia\",\"Libya\",\"Liechtenstein\",\"Lithuania\",\"Lucia\",\"Luxemburg\",\"Macedonian\",\"Macao\",\"Madagascar\",\"Malawi\",\"Malaysia\",\"Maldives\",\"Mali\",\"Malta\",\"Man island\",\"Martinique\",\"Mauritania\",\"Mauritius\",\"Mayotte\",\"Mexico\",\"Micronesia\",\"Moldova\",\"Monaco\",\"Mongolia\",\"Montserrat\",\"Morocco\",\"Mozambique\",\"Namibia\",\"Nauru\",\"Nepal\",\"New Caledonia\",\"New Zealand\",\"Nicaragua\",\"Niger\",\"Nigeria\",\"Niue\",\"Norfolk\",\"North Korea\",\"Norway\",\"Oman\",\"Pakistan\",\"Palau islands\",\"Palestine\",\"Panama\",\"Papua New Guinea\",\"Paraguay\",\"Peru\",\"Philippines\",\"Pitt Kaine\",\"Poland\",\"Portuguese\",\"Puerto Rico\",\"Qatar\",\"Reunion\",\"Romania\",\"Russia\",\"Rwanda\",\"Saint Kitts and nevis\",\"Saint Vincent and the grenadines\",\"Salvatore\",\"Samoa\",\"San Pierre and the micone islands\",\"San marino\",\"Sao Tome and principe\",\"Saudi Arabia\",\"Senegal\",\"Serbia, Montenegro\",\"Seychelles\",\"Sierra Leone\",\"Singapore\",\"Slovakia\",\"Slovenia\",\"Somalia\",\"South Africa\",\"South Georgia and the South Sandwich Islands\",\"Spain\",\"Sri Lanka\",\"St. helena\",\"Sultan\",\"Suriname\",\"Swaziland\",\"Sweden\",\"Switzerland\",\"Syria\",\"Taiwan\",\"Tajikistan\",\"Tanzania\",\"Thailand\",\"The British territory of the India ocean\",\"The Cayman Islands\",\"The Central African Republic\",\"The Cocos islands\",\"The Cook islands\",\"The Democratic Republic of Congo\",\"The Frank islands\",\"The French Southern territories\",\"The Marshall islands\",\"The Netherlands antilles\",\"The Northern Mariana islands\",\"The Oran islands\",\"The Republic of Dominica\",\"The Solomon islands\",\"The Turks and Kaiketesi islands\",\"The United States\",\"The Vatican\",\"The Virgin Islands, American\",\"The Virgin Islands, the British\",\"The island of Antigua and barbuda\",\"The islands\",\"Togo\",\"Tokelau\",\"Tonga\",\"Trinidad and Tobago\",\"Tristan Da khuon ha\",\"Tunisia\",\"Turkey\",\"Turkmenistan\",\"Tuvalu\",\"Uganda\",\"Ukraine\",\"United Arab Emirates, Arabia\",\"Uruguay\",\"Uzbekistan\",\"Vanuatu\",\"Venezuela\",\"Vietnam\",\"Wallis and futuna\",\"Yemen\",\"Zambia\",\"Zimbabwe\"]";
        List<String> data = new Gson().fromJson(str, new TypeToken<List<String>>() {}.getType());
        binding.registerSpinner.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, data));
        binding.registerSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = (TextView)view;
                if (position==0){
                    tv.setTextColor(getResources().getColor(R.color.grey1));
                }else {
                    tv.setTextColor(getResources().getColor(R.color.black));
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        binding.registerAgreement.setText(Tools.checkReadAutoLink(this));
        binding.registerAgreement.setMovementMethod(LinkMovementMethod.getInstance());

        launcher=registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode()==2){
                setResult(2);
                finish();
            }
            if (result.getResultCode()==3){
                setResult(4);
                finish();
            }
        });

    }





    private long mClickTime;
    private boolean checkDoubleClick() {
        boolean result= mClickTime < SystemClock.uptimeMillis() - 500;
        mClickTime = SystemClock.uptimeMillis();
        return result;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (Call call :calls) {
            call.cancel();
        }
        binding=null;
    }
}